<template>
  <div >
    <ListTab v-model="activeStatus" :show-header="!showMobilePage" :tabs="tabList" is-table @tabClick="handleTabClick" />
    <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
        <FilterInput
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          is-show-config
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus"/>
        <div class="table-top-opeator-bar">
          <btnGroup
            v-if="hasRouteAuth('crm:customerSettle:export')"
            ref="btnGroupRef"
            :list="[
              {label:'导出', type: 'export', auth: hasRouteAuth('crm:customerSettle:export'), exportApi:'/admin/client/settlement/list/export', exportName: '客户结算导出', exportNameLast: exportNameLast(), beforeExport: exportBeforeExport, refName:'exportRef'},
            ]"
            style="margin-right: 12px"
          />
          <createBtn v-if="hasRouteAuth('crm:customer:createSettle') || isAdmin" @click.native="createSettle"/>
        </div>
      </div>
      <div v-loading="listLoading" style="min-height: 100px;">
        <u-table
          v-if="list.items.length > 0"
          ref="tableRef"
          :data="list.items"
          :height="setTableHeight"
          :row-height="rowHeight(51)"
          :border="true"
          beautify-table
          header-drag-style
          use-virtual
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          hightlight-current-row
          @select="selectTable"
          @select-all="selectTable"
          @sort-change="sortMethod">
          <u-table-column
            :fixed="selectFixed"
            align="center"
            type="selection"
            width="50"/>
          <u-table-column align="left" label="结算单号" min-width="180">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.settleId" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.settleId }}</div>
                <span class="overflow" style="cursor:pointer;color:#406EFF" @click="toCheckBills(scope.row)">{{ scope.row.settleId || '--' }}</span>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="日期范围" min-width="200" prop="settleTimeRange" sortable="custom">
            <template slot-scope="scope">
              <span v-if="scope.row.settleTimeStart && scope.row.settleTimeEnd ">{{ scope.row.settleTimeStart | format('YYYY/MM/DD') }} - {{ scope.row.settleTimeEnd | format('YYYY/MM/DD') }}</span>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="客户名称" min-width="160">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.clientName" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.clientName }}</div>
                <span class="overflow">{{ scope.row.clientName || '--' }}</span>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="right" label="总金额(元)" min-width="140" prop="totalPrice" sortable="custom">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.totalPrice" :price="scope.row.totalPrice / 100" />
            </template>
          </u-table-column>
          <u-table-column align="right" label="总订单数" min-width="120" prop="totalOrder" sortable="custom">
            <template slot-scope="scope">
              <span>{{ scope.row.totalOrder || '--' }}</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="结算单状态" min-width="120">
            <template slot-scope="scope">
              <status-label :status="scope.row.status" :examine-status="scope.row.examineStatus" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建人" min-width="120">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.createUserId" :user-id="scope.row.createUserId" :label="scope.row.createUser" />
              <span v-else>{{ scope.row.createUser }}</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建时间" min-width="150" prop="createTime" sortable="custom">
            <template slot-scope="scope">
              <span class="overflow">{{ scope.row.createTime | format('YYYY/MM/DD HH:mm') }}</span>
            </template>
          </u-table-column>
          <u-table-column :align="operateAlign" :width="operateWidth" :fixed="operateFix" label="操作">
            <template slot-scope="scope">
              <div v-if="!showMobilePage" style="display:flex;">
                <div class="button-text" @click="toCheckBills(scope.row)">查看</div>
                <el-dropdown
                  v-if="scope.row.status !== 2"
                >
                  <div class="button-text bl">更多 <i class="el-icon-arrow-down"/></div>
                  <el-dropdown-menu slot="dropdown" style="margin-top:-10px;margin-right:15px;padding: 0;">
                    <el-dropdown-item v-if="scope.row.status === 3" style="width:100px;text-align: center" @click.native="editSettle(scope.row)">
                      <div>编辑</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="scope.row.status !== 2" :disabled="!(hasRouteAuth('crm:customer:customerDelete') || (userInfo.userName === scope.row.createUser && scope.row.status === 3))" style="width:100px;text-align: center" @click.native="toDel(scope)">
                      <div>删除</div>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <tableOperateBtn v-else>
                <el-dropdown-item style="width:90px;text-align: center" @click.native="toCheckBills(scope.row)">
                  <div style="font-size: 14px">查看</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.status === 3 && scope.row.status !== 2" style="width:90px;text-align: center" @click.native="editSettle(scope.row)">
                  <div>编辑</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.status === 3 && scope.row.status !== 2" :disabled="!(hasRouteAuth('crm:customer:customerDelete') || (userInfo.userName === scope.row.createUser && scope.row.status === 3))" style="width:90px;text-align: center" @click.native="toDel(scope)">
                  <div>删除</div>
                </el-dropdown-item>
              </tableOperateBtn>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else-if="!isInit" style="margin-bottom: 24px" />
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
        <el-pagination
          v-show="list.total > 0"
          :current-page.sync="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <fixed-pagination v-if="list.total > 0">
        <template v-if="showMobilePage">
          <FilterInput
            ref="FilterToolRef"
            v-model="paramsObj"
            :filter-list="filterList"
            show-search-btn
            is-show-config
            show-mobile-icon
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus"/>
          <createBtn v-if="hasRouteAuth('crm:customer:createSettle') || isAdmin" mobile-table @click.native="createSettle"/>
          <MoreOpeator
            v-if="hasRouteAuth('crm:customerSettle:export')"
            ref="moreOpeatorRef"
            :list="[
              {label:'导出', type: 'export', auth: hasRouteAuth('crm:customerSettle:export'), exportApi:'/admin/client/settlement/list/export', exportName: '客户结算导出', isBeforeExport: true, beforeExport: exportBeforeExport, exportNameLast: exportNameLast(), refName:'exportRef'},
            ]"
            style="margin-left: 12px;"
            label="批量操作"
            show-mobile-icon
          />
        </template>
        <template v-else>
          <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
          <span style="flex:1;"/>
          <el-pagination
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </template>
      </fixed-pagination>
    </div>
    <createSettle ref="createRef" :init="openInit" not-jump @getData="afterCreate" @openStatus="openStatus" />
  </div>
</template>

<script>
import setting from '@/assets/setting.png';
import ListTab from '@/components/ListTab';
import ImportButton from '@/components/ImportButton';
import createBtn from '@/components/Common/baseComponent/createBtn';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import createSettle from '@/components/Customer/createSettle';
import Dialog from '@/components/Customer/detail/dialog';
import StatusLabel from './module/statusLabel';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import { settlementTabs, settlementList, settlementDel, settlementDetail } from '@/api/customer.js';
import { moneyFilter } from '@/filters/number';
import { format } from '@/filters/date';
import { hasRouteAuth } from '@/utils/permission';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { mapState } from 'vuex';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import tableSelections from '@/mixins/tableSelections';

export default {
  name: 'SettleList',
  components: {
    ListTab,
    createBtn,
    StatusLabel,
    EmptyPlaceholder,
    ImportButton,
    createSettle,
    Dialog,
    btnGroup
  },
  filters: {
    format, moneyFilter
  },
  mixins: [TableAdaptive, mobileTable, tableSelections],
  data() {
    return {
      setting,
      tabList: [],
      paramsObj: {},
      filterList: [
        { keyword: 'clientName', name: '客户名称', type: 'input' },
        { keyword: 'createUser', name: '创建人', type: 'input' },
        { keyword: 'settleId', name: '结算单号', type: 'input' },
        { keyword: 'orderNum', name: '订单编号', type: 'input' },
        { keyword: 'totalAmount', name: '总金额', type: 'inputRange' },
        { keyword: 'createTime', name: '创建日期', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'settleTime', name: '结算日期', timeType: 'daterange', type: 'rangeDate' }
      ],
      page: 1,
      perPage: 20,
      listLoading: true,
      isInit: true,
      openInit: true,
      sortName: '',
      sortType: '',
      activeStatus: -1,
      tableRefName: 'tableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      isUmyTable: true,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInint: true
      },
      rangeKeyArr: [{
        attr: 'createTime',
        start: 'createStartTime',
        end: 'createEndTime',
        type: 'time'
      }, {
        attr: 'settleTime',
        start: 'settleStartTime',
        end: 'settleEndTime',
        type: 'time'
      }, {
        attr: 'totalAmount',
        start: 'totalAmountStart',
        end: 'totalAmountEnd',
        type: 'moneyFixedTwo'
      }]
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    tableOutsideHeight() {
      return 192;
    }
  },
  watch: {
    list: {
      handler(val) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val.items);
        });
      },
      deep: true
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'settleCustomer') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    next();
  },
  activated() {
    if (this.$route.meta.isChange) {
      this.fetchData();
    } else {
      const hasDefaultPresetFilter = this.$refs.FilterToolRef && this.$refs.FilterToolRef.hasDefaultPresetFilter;
      // 当预设的默认筛选且为第一次进入页面时，不请求数据（会在 filterTool 组件进行筛选）
      if (!this.isInit || !hasDefaultPresetFilter) {
        this.paramsObj = {};
        this.activeStatus = this.$route.query.status !== undefined ? Number(this.$route.query.status) : -1;
        if (this.$route.query.examineStatus || this.$route.query.examineStatus === 0) {
          this.$set(this.paramsObj, 'examineStatus', this.$route.query.examineStatus);
        }
        if (this.$route.query.name) {
          this.$set(this.paramsObj, 'clientName', this.$route.query.name);
        }
        this.fetchData(true);
      }
    }
    // 从渠道订单跳转过来，带有客户名称和订单id
    const orderId = this.$route.query.orderId || null;
    const clientCompany = this.$route.query.clientName || null;
    if (orderId && clientCompany) {
      this.openInit = true;
      setTimeout(() => {
        this.createSettle();
      }, 1000);
    }
  },
  methods: {
    openStatus(status) {
      this.openInit = status;
    },
    exportNameLast() {
      const date = new Date().getTime();
      return `${format(date, 'YYYYMMDDHHmmss').substring(8)}`;
    },
    hasRouteAuth,
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
    },
    handleCurrentChange(val) {
      this.page = val;
      this.fetchData();
    },
    // 新增编辑结算单后跳转到结算单详情页
    afterCreate(id) {
      this.toCheckBills({ id });
    },
    toCheckBills(item) { // 查看单据
      this.$router.push({
        name: 'settleCustomer',
        params: { id: item.id || 1 }
      });
    },
    toDel(scope) {
      this.$confirm('是否确定删除该结算单', '', {
        iconClass: 'del-icon',
        customClass: 'del-message del-message-cancel',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        type: 'warning'
      }).then(() => {
        settlementDel(scope.row.id).then(res => {
          this.$message.success('删除成功');
          if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.list.total) {
            this.page--;
          }
          this.fetchData(true);
        }, result => {
          // this.$message.error(result.message);
        });
      }).catch(() => {
        return false;
      });
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    formatParams() {
      const paramsObj = JSON.parse(JSON.stringify(this.paramsObj));
      paramsRangeFormat(this.rangeKeyArr, paramsObj);
      paramsObj.status = this.activeStatus;
      paramsObj.page = this.page || 1;
      paramsObj.perPage = this.perPage || 10;
      return paramsObj;
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      this.getTabList();
      this.listLoading = true;
      const params = this.formatParams();
      params.sortName = this.sortName || '';
      params.sortType = this.sortType || '';
      settlementList(params).then(res => {
        this.isInit = false;
        if (res.code === 200) {
          this.list = res.data;
        }
        this.list.isInint = false;
        this.listLoading = false;
      }, result => {
        this.listLoading = false;
      }).catch(e => {
        console.error(e);
      });
    },
    handleExport() {
      const params = this.formatParams();
      params.ids = this.multipleSelectionAll.map(i => i.id).join(',');
      if (!this.showMobilePage && this.$refs.btnGroupRef) {
        this.$refs['btnGroupRef'].btnExportDirect(params);
      } else if (this.showMobilePage && this.$refs.moreOpeatorRef) {
        this.$refs.moreOpeatorRef.btnExport(params, 'exportRef');
      }
    },
    exportBeforeExport() {
      if (!this.multipleSelectionAll || this.multipleSelectionAll.length === 0) {
        this.$confirm('是否导出所有客户结算数据?', {
          confirmButtonText: '确定',
          type: 'warning',
          showClose: false,
          center: true,
          iconClass: 'charge-icon',
          customClass: 'del-message del-message-cancel'
        }).then(() => {
          this.handleExport();
        }).catch(() => {
          return;
        });
      } else {
        this.handleExport();
      }
    },
    // 表格tab切换按钮
    handleTabClick() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    async getTabList() {
      try {
        const result = await settlementTabs();
        if (result.code === 200) {
          this.tabList = result.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 编辑结算单
    async editSettle(item) {
      try {
        const res = await this.getSettleData(item.id);
        if (this.$refs.createRef) this.$refs.createRef.openDialog(res, true);
      } catch (error) {
        console.log('error');
      }
    },
    // 创建结算单
    createSettle() {
      if (this.$refs.createRef) this.$refs.createRef.openDialog();
    },
    getSettleData(settlementId) {
      return new Promise(async(resolve, reject) => {
        try {
          const result = await settlementDetail({ id: settlementId });
          if (result.code === 200) {
            resolve(result.data);
          } else { reject(); }
        } catch (error) {
          reject(error);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.table-list {
  margin: 16px 16px 0 16px;
  padding: 24px 24px 55px 24px;
  background-color: #fff;
  overflow: hidden;
  .create-btn {
    display: flex;
    cursor: pointer;
    align-items: center;
    justify-content: center;
    width:110px;
    height:32px;
    background:rgba(64,110,255,1);
    border-radius:4px;
    font-size:14px;
    font-weight:500;
    color:rgba(255,255,255,1);
    line-height:14px;
  }
}
.pagination-area {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.overflow {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>
